import matplotlib.pyplot as plt
from jili.core import sendemail as mail
from jili.core.convert import converttype
from jili.calc.status import status
import pandas as pd
from jili.tool.state import ismongo
if ismongo:
    from jili.data import db as dba
def genkline(obj,name="Kline"):
    a=dba.getkline1d_index(obj)
    del a["_id"]
    del a["windcode"]
    del a["obj"]
    del a["marketcode"]
    kline(a,name,True)
def kline_bbands(a,name="Kline",iscalc=False):
    from pyecharts import Kline,Line,Grid,Bar,Overlap,online
    online()
    kline = Kline("RB")
    x = a["timekey"].apply(lambda x: str(x)[:10]).tolist()
    #k_plot_value = a.apply(lambda record: [record['open'], record['close'], record['low'], record['high']], axis=1).tolist()
    kline.add(
        "rb日K",
        x,
        a.loc[:,["open", "close", "low", "high"]].values.tolist(),
        mark_point=["max","min"],
        is_datazoom_show=True,
        datazoom_type="both",
        tooltip_axispointer_type="cross",
        tooltip_trigger="axis",
        datazoom_range=[94,100],
        datazoom_xaxis_index=[0,1]
    )
    line1 = Line()
    if iscalc:
        import talib
        a["upperband2"], a["middleband"], a["lowerband2"] = talib.BBANDS(a["close"],16)
        a["upperband1"], a["middleband"], a["lowerband1"] = talib.BBANDS(a["close"],16,1,1)
        a["upperband3"], a["middleband"], a["lowerband3"] = talib.BBANDS(a["close"],16,3,3)
        a["VMA5"]=talib.SMA(a["volume"].values,5)
        a["VMA10"]=talib.SMA(a["volume"].values,10)
    line1.add("upperband3", x, a["upperband3"].values.tolist(),is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("upperband2", x, a["upperband2"].values.tolist(),is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("upperband1", x, a["upperband1"].values.tolist(),is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("middleband", x, a["middleband"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("lowerband1", x, a["lowerband1"].values.tolist(),is_symbol_show=False,  is_smooth=True,tooltip_tragger="axis")
    line1.add("lowerband2", x, a["lowerband2"].values.tolist(),is_symbol_show=False,  is_smooth=True,tooltip_tragger="axis")
    line1.add("lowerband3", x, a["lowerband3"].values.tolist(),is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    overlap1 = Overlap()
    overlap1.add(kline)
    overlap1.add(line1)
    bar1=Bar()
    bar1.add("成交量",x,a["volume"].values.tolist(),is_legend_show=False,tooltip_tragger="axis")
    line2 = Line()
    line2.add("VMA5", x, a["VMA5"].values.tolist(),is_symbol_show=False, is_smooth=True,is_legend_show=False,tooltip_tragger="axis")
    line2.add("VMA10", x, a["VMA10"].values.tolist(), is_symbol_show=False, is_smooth=True,is_legend_show=False,tooltip_tragger="axis")
    """
    kline1 = Kline("RB1")
    kline1.add(
        "rb日K",
        x,
        a1.loc[:,["open", "close", "low", "high"]].values.tolist(),
        mark_point=["max","min"],
        is_datazoom_show=True,
        datazoom_type="both",
        tooltip_axispointer_type="cross",
        tooltip_trigger="axis",
        datazoom_range=[94,100],
        datazoom_xaxis_index=[0,1]
    )
    line11 = Line()
    if iscalc:
        import talib
        a1["upperband2"], a1["middleband"], a1["lowerband2"] = talib.BBANDS(a1["close"],16)
        a1["upperband1"], a1["middleband"], a1["lowerband1"] = talib.BBANDS(a1["close"],16,1,1)
        a1["VMA5"]=talib.SMA(a1["volume"].values,5)
        a1["VMA10"]=talib.SMA(a1["volume"].values,10)
    line11.add("upperband2", x, a1["upperband2"].values.tolist(),is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line11.add("upperband1", x, a1["upperband1"].values.tolist(),is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line11.add("middleband", x, a1["middleband"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line11.add("lowerband1", x, a1["lowerband1"].values.tolist(),is_symbol_show=False,  is_smooth=True,tooltip_tragger="axis")
    line11.add("lowerband2", x, a1["lowerband2"].values.tolist(),is_symbol_show=False,  is_smooth=True,tooltip_tragger="axis")
    "
    overlap11 = Overlap()
    overlap11.add(kline1)
    overlap11.add(line11)
    """
    overlap2 = Overlap()
    overlap2.add(bar1)
    overlap2.add(line2)
    grid = Grid(page_title=name,width=1900,height=1000)
    grid.add(overlap1, grid_bottom="20%")
    grid.add(overlap2, grid_top="80%")
    """
    grid.add(overlap1, grid_bottom="60%")
    grid.add(overlap2, grid_bottom="40%",grid_top="40%")
    grid.add(overlap11, grid_top="60%")
    """
    grid.render(name+".html")
def kline1m(a,name="Kline1m",iscalc=True,isopen=True):
    from pyecharts import Kline,Line,Grid,Bar,Overlap,online
    online()
    kline = Kline("RB")
    x = a["timekey"].apply(lambda x: str(x)[:19]).tolist()
    #k_plot_value = a.apply(lambda record: [record['open'], record['close'], record['low'], record['high']], axis=1).tolist()
    kline.add(
        "rb日K",
        x,
        a.loc[:,["open", "close", "low", "high"]].values.tolist(),
        mark_point=["max","min"],
        is_datazoom_show=True,
        datazoom_type="both",
        tooltip_axispointer_type="cross",
        tooltip_trigger="axis",
        datazoom_range=[94,100],
        datazoom_xaxis_index=[0,1]
    )
    line1 = Line()
    if iscalc:
        import talib
        a["MA5"]=talib.SMA(a["close"].values,5)
        a["MA10"]=talib.SMA(a["close"].values,10)
        a["MA20"]=talib.SMA(a["close"].values,20)
        a["MA30"]=talib.SMA(a["close"].values,30)
        a["MA60"]=talib.SMA(a["close"].values,60)
        a["MA120"]=talib.SMA(a["close"].values,120)
        a["VMA5"]=talib.SMA(a["volume"].values,5)
        a["VMA10"]=talib.SMA(a["volume"].values,10)
    line1.add("close", x, a["close"].values.tolist(),is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("MA5", x, a["MA5"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("MA10", x, a["MA10"].values.tolist(),is_symbol_show=False,  is_smooth=True,tooltip_tragger="axis")
    line1.add("MA20", x, a["MA20"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("MA30", x, a["MA30"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("MA60", x, a["MA60"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("MA120", x, a["MA120"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    overlap1 = Overlap()
    overlap1.add(kline)
    overlap1.add(line1)
    bar1=Bar()
    bar1.add("成交量",x,a["volume"].values.tolist(),is_legend_show=False,tooltip_tragger="axis")
    line2 = Line()
    line2.add("VMA5", x, a["VMA5"].values.tolist(),is_symbol_show=False, is_smooth=True,is_legend_show=False,tooltip_tragger="axis")
    line2.add("VMA10", x, a["VMA10"].values.tolist(), is_symbol_show=False, is_smooth=True,is_legend_show=False,tooltip_tragger="axis")
    overlap2 = Overlap()
    overlap2.add(bar1)
    overlap2.add(line2)
    grid = Grid(page_title=name,width=1900,height=900)
    grid.add(overlap1, grid_bottom="20%")
    grid.add(overlap2, grid_top="80%")
    grid.render(name+".html")
    if isopen:
        openweb(name+".html")
def kline(a,name="Kline",iscalc=False,isopen=True):
    from pyecharts import Kline,Line,Grid,Bar,Overlap,online
    online()
    kline = Kline("RB")
    x = a["timekey"].apply(lambda x: str(x)[:10]).tolist()
    #k_plot_value = a.apply(lambda record: [record['open'], record['close'], record['low'], record['high']], axis=1).tolist()
    kline.add(
        "rb日K",
        x,
        a.loc[:,["open", "close", "low", "high"]].values.tolist(),
        mark_point=["max","min"],
        is_datazoom_show=True,
        datazoom_type="both",
        tooltip_axispointer_type="cross",
        tooltip_trigger="axis",
        datazoom_range=[94,100],
        datazoom_xaxis_index=[0,1]
    )
    line1 = Line()
    if iscalc:
        import talib
        a["MA5"]=talib.SMA(a["close"].values,5)
        a["MA10"]=talib.SMA(a["close"].values,10)
        a["MA20"]=talib.SMA(a["close"].values,20)
        a["MA30"]=talib.SMA(a["close"].values,30)
        a["MA60"]=talib.SMA(a["close"].values,60)
        a["MA120"]=talib.SMA(a["close"].values,120)
        a["VMA5"]=talib.SMA(a["volume"].values,5)
        a["VMA10"]=talib.SMA(a["volume"].values,10)
    line1.add("close", x, a["close"].values.tolist(),is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("MA5", x, a["MA5"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("MA10", x, a["MA10"].values.tolist(),is_symbol_show=False,  is_smooth=True,tooltip_tragger="axis")
    line1.add("MA20", x, a["MA20"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("MA30", x, a["MA30"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("MA60", x, a["MA60"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    line1.add("MA120", x, a["MA120"].values.tolist(), is_symbol_show=False, is_smooth=True,tooltip_tragger="axis")
    overlap1 = Overlap()
    overlap1.add(kline)
    overlap1.add(line1)
    bar1=Bar()
    bar1.add("成交量",x,a["volume"].values.tolist(),is_legend_show=False,tooltip_tragger="axis")
    line2 = Line()
    line2.add("VMA5", x, a["VMA5"].values.tolist(),is_symbol_show=False, is_smooth=True,is_legend_show=False,tooltip_tragger="axis")
    line2.add("VMA10", x, a["VMA10"].values.tolist(), is_symbol_show=False, is_smooth=True,is_legend_show=False,tooltip_tragger="axis")
    overlap2 = Overlap()
    overlap2.add(bar1)
    overlap2.add(line2)
    grid = Grid(page_title=name,width=1900,height=900)
    grid.add(overlap1, grid_bottom="20%")
    grid.add(overlap2, grid_top="80%")
    grid.render(name+".html")
    if isopen:
        openweb(name+".html")
def showtooltip(params):
    return params.name + ' : ' + params.value
    
def countseq(df,field=[]):
    a={}
    b={}
    d={}
    rst={}
    for i in field:
        rst[i]=[]
        a[i]=0
        b[i]=0
        d[i]=0
    df=converttype(df,"list")
    for i in df:
        for j in field:
            if b[j]!=0:
                if d[j]==1:
                    if i[j]>=b[j]:
                        a[j]=a[j]+1
                    else:
                        d[j]=-1
                        a[j]=a[j]+1
                        rst[j].append(a[j])
                        a[j]=0
                elif d[j]==-1:
                    if i[j]<=b[j]:
                        a[j]=a[j]-1
                    else:
                        d[j]=1
                        a[j]=a[j]-1
                        rst[j].append(a[j])
                        a[j]=0
                else:
                    if i[j]>b[j]:
                        d[j]=1
                        a[j]=a[j]+1
                    else:
                        d[j]=-1
                        a[j]=a[j]-1
                b[j]=i[j]
            else:
                b[j]=i[j]
    return rst
def reportseqcountdescrib(df,field={}):
    a={}
    b={}
    d={}
    rst={}
    for i in field:
        rst[i]=[]
        a[i]=0
        b[i]=0
        d[i]=0
    df=converttype(df,"list")
    for i in df:
        for j in field:
            if b[j]!=0:
                if d[j]==1:
                    if i[j]>=b[j]:
                        a[j]=a[j]+1
                    else:
                        d[j]=-1
                        a[j]=a[j]+1
                        rst[j].append(a[j])
                        a[j]=0
                elif d[j]==-1:
                    if i[j]<=b[j]:
                        a[j]=a[j]+1
                    else:
                        d[j]=1
                        a[j]=a[j]+1
                        rst[j].append(a[j])
                        a[j]=0
                else:
                    if i[j]>b[j]:
                        d[j]=1
                        a[j]=a[j]+1
                    else:
                        d[j]=-1
                        a[j]=a[j]+1
                b[j]=i[j]
            else:
                b[j]=i[j]
    return rst
def dfdiscrib(df,field=[],name="report"):
    a=df
    if field:
        a=a.loc[:,field]
    discrib(a,name)
def discrib(df,name="report",htmloremail="html",isopen=False):
    df = converttype(df,"df")
    df=df.dropna()
    if htmloremail=="html":
        report_to_html(name,df)
    elif htmloremail=="email":
        report_to_email(name,df)
    else:
        report_to_html(name,df)
        report_to_email(name,df)
    if isopen:
        openweb(name+".html")
def openweb(url):
    import webbrowser,platform
    if (platform.system()=='Windows') or (platform.system()=='Linux'):
        webbrowser.open(url, new=0, autoraise=True)
    else:
        import os
        os.system("open "+url)
def kline_discrib(obj,field=[["high","low"],["close","open"]],cu="kline1dindex",db="kline1d",htmloremail="html",isopen=False):
    field0=[]
    for i in field:
        for j in i:
            field0.append(j)
    ad=dba.getdb(cu,find={"obj":obj},field=field0,db=db,datatype="DF")
    loc_columuns=[]
    for i in field:
        f1=i[0]
        f2=i[1]
        name=i[0]+"-"+i[1]
        nameabs=name+".abs"
        loc_columuns.append(name)
        loc_columuns.append(nameabs)
        ad[name]=ad[f1]-ad[f2]
        ad[nameabs]=abs(ad[name])
    ads=ad.loc[:,loc_columuns]
    reportname="report."+obj+"."+cu
    if htmloremail=="html":
        report_to_html(reportname,ads)
    elif htmloremail=="email":
        report_to_email(reportname,ads)
    else:
        report_to_html(reportname,ads)
        report_to_email(reportname,ads)
    if isopen:
        import webbrowser
        webbrowser.open(reportname+".html", new=0, autoraise=True)
def report_to_html(html,df,mode="w"):
    df=converttype(df,"df")
    html0=html+".html"
    if mode=="w":
        f = open(html0,mode,encoding='utf8')
        h=headhtml(html)
    else:
        f = open(html0,mode,encoding='utf8')
        h=""
    pd.set_option('max_colwidth',200)
    rst=df.apply(status)
    h=h+addtext(html+"统计描述如下","h1")
    h=h+addtable(rst)
    plt.rcParams['savefig.dpi'] = 120 #图片像素
    plt.rcParams['figure.dpi'] = 120 #分辨率
    for i in df.columns:
        plt.figure()
        plt.hist(df[i],bins=100)
        digname=str(id(df))+"."+str(i)+".png"
        plt.savefig(digname)
        h=h+addtext(digname)
        h=h+addfig(digname)
    h=h+endhtml()
    for eachline in h:
         f.write(eachline)
    f.close()
def report_to_email(name,df,tomail=[]):
    h=headhtml(name)
    pd.set_option('max_colwidth',200)
    rst=df.apply(status)
    h=h+addtext(name+"统计描述如下","h1")
    h=h+addtable(rst)
    plt.rcParams['savefig.dpi'] = 120 #图片像素
    plt.rcParams['figure.dpi'] = 120 #分辨率
    emailfig=[]
    for i in df.columns:
        plt.figure()
        plt.hist(df[i],bins=100)
        digname=str(id(df))+"."+str(i)+".png"
        plt.savefig(digname)
        emailfig.append(digname)
    h=h+endhtml()
    mail.send("统计报告"+name,h,fig=emailfig,tomail=tomail)        
def headhtml(title):
    head0="""<html>
        <head>
            <meta charset="utf-8">
            <title>"""+title+"""</title>
        </head>
        <body>"""
    return head0
def endhtml():
    head0="""
            </body>
        <html>"""
    return head0
def addtext(text,headtype="h4"):
    return """<div align="center">
            <"""+headtype+""" align="center">"""+text+"""</"""+headtype+""">
        </div>"""
def addtable(table):
    if not isinstance(table,pd.DataFrame):
        t=converttype(table,"df")
    else:
        t=table
    if isinstance(t,pd.DataFrame):
        pd.set_option('max_colwidth',200)
        a =t.to_html()
        a= """<div align="center">
                """+a+"""
            </div>"""
    else:
        a=""
    return a
def addfig(fig):
    return """<div align="center">
            <img src="""+fig+"""  alt="no fig" />
        </div>"""